package com.twu.biblioteca;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class BibliotecaApp {
    public Messages messages;
    public Menu menu;
    public Biblioteca biblioteca;

    public BibliotecaApp(Messages message, Menu menu, Biblioteca biblioteca) {
        this.messages = message;
        this.menu = menu;
        this.biblioteca = biblioteca;
    }

    public static void main(String[] args) {
        ArrayList<Option> options = Option.getAllOptions();
        ArrayList<Book> books = setBooks();
        ArrayList<User> users = setDefaultUsers();

        BibliotecaApp bibliotecaApp = new BibliotecaApp(new Messages(), new Menu(options), new Biblioteca(books, new Messages(), users));
        bibliotecaApp.welcome();

        Option option = new Option();
        do {
            User user = new User();
            bibliotecaApp.displayMenu(bibliotecaApp.menu, user);
            System.out.print("Choice one option: ");
            String readInputOption = null;

            try{
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                readInputOption = bufferedReader.readLine();
                int intOption = Integer.parseInt(readInputOption);
                option = Option.createFrom(intOption);
            }
            //Need fix if user dont select any option
            catch (NullPointerException e){
                System.out.println("Invalid Option: " + readInputOption);
            }
            catch (NumberFormatException e){
                System.out.println("Not a valid number: " + readInputOption);
            }
            catch (IOException e){
                System.out.println("Unexpected IO ERROR: " + e);
            }
            finally {
                if (bibliotecaApp.menu.validateOption(option)){
                    if (option.equals(Option.LIST_ALL)){
                        String strAllBooks = bibliotecaApp.biblioteca.listAllBooks();
                        System.out.println(strAllBooks);
                    } else {
                        if (option.equals(Option.MEMBERSHIP_INFO)){
                            String detailsMembership = bibliotecaApp.biblioteca.detailsMembership(user);
                            System.out.println(detailsMembership);
                        } else {
                            if (option.equals(Option.USER_LOGIN)) {
                                if (user.isLogged()){
                                    bibliotecaApp.toggleLogin(user);
                                }
                            } else {
                                if (user.isLogged()){
                                    if (option.equals(Option.RESERVE_BOOK)) {
                                        Book book = bibliotecaApp.selectBook(bibliotecaApp.biblioteca.books);
                                        bibliotecaApp.biblioteca.reserveBook(book);
                                    }
                                } else {
                                    if(!option.equals(Option.EXIT))
                                        System.out.println(bibliotecaApp.messages.getNeedLogin());
                                }
                            }
                        }
                    }
                } else {
                    System.out.println(bibliotecaApp.messages.getInvalidOption());
                }
            }
        } while(!option.equals(Option.EXIT));

        System.out.println(bibliotecaApp.messages.getMessageExit());
    }

    private User toggleLogin(User user) {
        if (user.isLogged()){
            user.logout();
        } else {
            String username = null;
            while (username == null){
                System.out.print("Enter your USERNAME: ");
                try {
                    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
                    String readUsername = is.readLine();

                } catch (IOException e){
                    System.out.println("Unexpected IO ERROR: " + e);
                }
            }
        }
        return user;
    }

    public void welcome() {
        System.out.println(messages.getWelcome());
    }

    public void displayMenu(Menu menu, User user){
        System.out.println(menu.outMenu(user.isLogged()));
    }

    public Book selectBook(ArrayList<Book> books){
        String readId = null;
        int idBook = 0;

        System.out.print("Enter the ID number: ");
        try{
            BufferedReader is = new BufferedReader(
                    new InputStreamReader(System.in));
            readId = is.readLine();
            idBook = Integer.parseInt(readId);
        }
        catch (NumberFormatException e) {
            String[] idBookSplit = readId.split("ID");
            idBook = Integer.parseInt(readId);
        }
        catch (IOException e) {
            System.out.println("Unexpected IO ERROR: " + e);
        }
        finally {
            Book book = books.get(idBook-1);
            return book;
        }
    }


    private static ArrayList<Book> setBooks() {
        ArrayList<Book> books = new ArrayList<Book>();
        books.add(new Book(1, "Teste - 1"));
        books.add(new Book(2, "Teste - 2"));
        books.add(new Book(3, "Teste - 3"));
        books.add(new Book(4, "Teste - 4"));

        return books;
    }

    private static ArrayList<User> setDefaultUsers(){
        int max = 5;
        List<String> names = new LinkedList<String>();
        names.add("Tania");
        names.add("Marcelo");
        names.add("Thais");
        names.add("Guilherme");
        names.add("Otávio");
        names.add("Alisson");

        List<String> emails = new LinkedList<String>();
        emails.add("tkds@gmail.com");
        emails.add("turn@gmail.com");
        emails.add("all@gmail.com");
        emails.add("vic@gmail.com");
        emails.add("tks@gmail.com");
        emails.add("sayadn@gmail.com");

        List<String> phones = new LinkedList<String>();
        phones.add("30759999");
        phones.add("32157899");
        phones.add("37890098");
        phones.add("36729980");
        phones.add("32896544");
        phones.add("");

        Random rand = new Random();

        ArrayList<User> users = new ArrayList<User>();
        for (int i = 0; i < max; ++i){
            users.add(new User());

            User user = users.get(i);
            user.setUsername();
            user.setPassword(user.getUsername());
            int index = rand.nextInt(names.size());
            user.setName(names.get(index));

            index = rand.nextInt(emails.size());
            user.setEmail(emails.get(index));

            user.setPhone(String.valueOf(generateRandom(8)));
        }
        return users;
    }

    public static long generateRandom(int length) {
        Random random = new Random();
        char[] digits = new char[length];
        digits[0] = (char) (random.nextInt(9) + '1');
        for (int i = 1; i < length; i++) {
            digits[i] = (char) (random.nextInt(10) + '0');
        }
        return Long.parseLong(new String(digits));
    }
}
